package com.itheima.reggie.controller;

import com.alibaba.druid.sql.visitor.functions.Nil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: hamo
 * @Create by: 渭北彭于晏
 * @Date: 2021/11/3 15:15
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品添加
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }


    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {

        //根据条件进行分页查询
        IPage<Dish> paginfor = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);
        IPage<Dish> result = dishService.page(paginfor, wrapper);

        List<Dish> dishList = result.getRecords();//获取查询后的所有数据
        List<Dish> dtoList = dishList.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);//将dish转换为dishDto
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);//根据categoryId获取category对象
            dishDto.setCategoryName(category.getName());//通过category对象获取菜品分类名称并封装进dishDto中
            return dishDto;
        }).collect(Collectors.toList());

        result.setRecords(dtoList);
        return R.success(result);
    }

    /**
     * 菜品修改数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getByID(@PathVariable("id") Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改
     *
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateByIdDto(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改完成");
    }

    @DeleteMapping
    public R deleteById(Long ids) {
        dishService.removeByIdWithDto(ids);
        return R.success("删了");
    }


    /**
     * 根据菜品分类id查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R getDish(Dish dish) {

        List<DishDto> dishDtoList = null;

        //构造key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        //定义redis中获取数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null){
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1);//根据categoryI且状态为1
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);//sort排序,如不可则以修改时间为准
        List<Dish> list = dishService.list(wrapper);

         dishDtoList = list.stream().map((adish) -> {
            Long dishId = adish.getId();
            LambdaQueryWrapper<DishFlavor> querywrapper = new LambdaQueryWrapper<>();
            querywrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(querywrapper);

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(adish, dishDto);//封装菜品信息
            dishDto.setFlavors(dishFlavors);//封装口味信息

            Category category = categoryService.getById(adish.getCategoryId());
            dishDto.setCategoryName(category.getName());//封装分类名称
            return dishDto;

        }).collect(Collectors.toList());

         //如果不存在,需要查询数据库,将查询到的菜品数据存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
